import ColorUISdk from '../../mp-sdk/index'

const sdk = new ColorUISdk({
  env: 'dev',
  version: '1.0.0',
  api: {
    dev: { 
      url: 'http://192.168.134.31:5000'
    }
  }
})

Page({
  data: {
    feedbackList: [] as any[],
    loading: true
  },

  onLoad() {
    this.getFeedbackHistory()
  },

  onShow() {
    // 页面显示时重新加载数据
    this.getFeedbackHistory()
  },

  // 获取反馈历史
  async getFeedbackHistory() {
    const userInfo = wx.getStorageSync('userInfo')
    // 改动1：将原来的_id改为统一使用user_id字段，与后端保持一致
    const userId = userInfo?.user_id  
    
    if (!userId) {
      wx.navigateTo({
        url: '/pages/login/login'
      })
      return
    }
    
    try {
      this.setData({ loading: true })
      
      // 改动2：API路径添加/api前缀，符合接口规范
      const res = await sdk.request({
        url: `/api/feedback/history?userId=${userId}`,
        method: 'GET'
      })
      
      if (res.code === 0) {
        // 格式化时间
        const formattedList = res.data.map((item: any) => ({
          ...item,
          createTime: this.formatTime(item.createTime)
        }))
        
        this.setData({
          feedbackList: formattedList,
          loading: false
        })
      } else {
        this.setData({ loading: false })
        wx.showToast({
          title: res.msg || '获取历史记录失败',
          icon: 'none'
        })
      }
    } catch (error) {
      this.setData({ loading: false })
      wx.showToast({
        title: '网络错误',
        icon: 'none'
      })
    }
  },

  // 格式化时间
  formatTime(timeString: string) {
    const date = new Date(timeString)
    return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
  },

  // 查看详情
  viewDetail(e: any) {
    const { id } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/feedback-detail/feedback-detail?id=${id}`
    })
  }
})
